package com.ztn.iot.zhonghaichi.push;

import com.ztn.base.util.common.HttpClientTool;
import com.ztn.iot.zhonghaichi.properties.ZhcProperties;
import com.ztn.iot.zhonghaichi.push.req.TokenGetReq;
import com.ztn.iot.zhonghaichi.push.res.TokenRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class TokenGetApi {

    @Autowired
    private ZhcProperties zhcProperties;

    private static final Map<String, Object> tokenMap = new HashMap<>(2);


    public static Map<String, Object> getHeaders(String baseUrl) {
        Object token = tokenMap.get(baseUrl);
        if (null == token) {
            log.error("null == token");
            return null;
        }
        Map<String, Object> HEADERS = new HashMap<>(2);
        HEADERS.put("Authorization", token);
        return HEADERS;
    }

    public void setToken(String baseUrl, String token) {
        tokenMap.put(baseUrl, token);
    }

    public void getToken() {
        zhcProperties.getZhcAuths().forEach(zhmAuth -> {
            TokenGetReq req = new TokenGetReq();
            req.setUsername(zhmAuth.getUserName());
            req.setUsercode(zhmAuth.getPassword());

            final TokenRes res = HttpClientTool.getForObject(zhmAuth.getBaseUrl() + TokenGetReq.URL + "?username=" + req.getUsername() + "&usercode=" + req.getUsercode(), TokenRes.class,null);
            if (null != res && StringUtils.hasText(res.getData())) {
                log.info("update {} token {}", zhmAuth.getBaseUrl(), res.getData());
                setToken(zhmAuth.getBaseUrl(), res.getData());
            } else {
                log.error("{} can not get token", zhmAuth.getBaseUrl());
            }
        });
    }
}
